package linkedlist;

/**
 * @author 十八岁讨厌编程
 * @date 2025/6/27 21:11
 * @PROJECT_NAME leetcode
 * @description
 */

public class Solution19 {


    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode reverseList = reverseList(head);
        ListNode deleteList = deleteAtCount(reverseList, n);
        return reverseList(deleteList);
    }

    public ListNode reverseList(ListNode head) {
        ListNode reverseResultVirtualHead = new ListNode();
        ListNode pointer = head;
        while (pointer != null) {
            ListNode currentNode = new ListNode(pointer.val, null);
            currentNode.next = reverseResultVirtualHead.next;
            reverseResultVirtualHead.next = currentNode;
            pointer = pointer.next;
        }
        return reverseResultVirtualHead.next;
    }

    public ListNode deleteAtCount(ListNode head, int count) {
        ListNode virtualHead = new ListNode(-1, head);
        ListNode pointer = virtualHead;
        while (count > 0 && pointer.next != null) {
            if (count == 1) {
                pointer.next = pointer.next.next;
            }
            count -= 1;
            pointer = pointer.next;
        }
        return virtualHead.next;
    }


}
